package services

import (
    "encoding/json"
    "fmt"
    "time"
    "volux/utils"
)

type PerfStoreService struct {
    etcdClient *utils.EtcdClient
}

type PerfData struct {
    Resource  string                 `json:"resource"`
    Metrics   map[string]float64     `json:"metrics"`
    Tags      map[string]string      `json:"tags"`
    Timestamp time.Time             `json:"timestamp"`
}

func NewPerfStoreService(etcdClient *utils.EtcdClient) *PerfStoreService {
    return &PerfStoreService{
        etcdClient: etcdClient,
    }
}

func (ps *PerfStoreService) StorePerfData(data PerfData) error {
    // 构建键名: /perf/{resource}/{timestamp}
    key := fmt.Sprintf("/perf/%s/%d", data.Resource, data.Timestamp.UnixNano())
    
    // 序列化数据
    value, err := json.Marshal(data)
    if err != nil {
        return err
    }

    // 设置一天的TTL
    return ps.etcdClient.PutWithTTL(key, string(value), 86400)
}

func (ps *PerfStoreService) GetPerfData(resource string, start, end time.Time) ([]PerfData, error) {
    prefix := fmt.Sprintf("/perf/%s/", resource)
    events, err := ps.etcdClient.GetWithPrefix(prefix)
    if err != nil {
        return nil, err
    }

    var results []PerfData
    for _, event := range events {
        var data PerfData
        if err := json.Unmarshal([]byte(event.Kv.Value), &data); err != nil {
            continue
        }
        
        // 过滤时间范围
        if data.Timestamp.After(start) && data.Timestamp.Before(end) {
            results = append(results, data)
        }
    }

    return results, nil
}
